package com.example.demo.ordernumber;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.MutableDateTime;
import org.joda.time.Seconds;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.UUID;

/**
 * 工具类
 *
 * @author tsangzacks
 */
@Slf4j
public class JUtils {
    final static String DEFAULT_FORMAT = "yyyy-MM-ddTHH:mm:ss";
    final static String NORMAL_FORMAT = "yyyy-MM-dd HH:mm:ss";

    /**
     * 获取 uuid，移除「-」
     *
     * @return uuid
     */
    public static String uuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 获取 16 位 uuid
     *
     * @return uuid
     */
    public static String uuid16() {
        return uuid().substring(0, 16);
    }

    /**
     * 数值根据小数位数往下取值
     *
     * @param amount 数值
     * @param digit  小数位数
     * @return double
     */
    public static double roundDown(double amount, int digit) {
		BigDecimal decimal = BigDecimal.valueOf(amount);;
        decimal = decimal.setScale(digit, BigDecimal.ROUND_DOWN);
        return decimal.doubleValue();
    }

    /**
     * 返回不带 + 号的手机区号
     *
     * @param idd 手机区号
     * @return 86
     */
    public static String simpleAreaCode(String idd) {
        return idd.trim().replace("+", "");
    }

    /**
     * 获取 UTC 时间戳，单位秒
     *
     * @return 时间戳
     */
    public static int timeStamp() {
        return (int) (System.currentTimeMillis() / 1000);
    }

    /**
     * 获取东八区时间 yyyy-MM-dd 格式
     *
     * @return 2020-02-01
     */
    public static String yyyyMMdd() {
        DateTime local = DateTime.now(DateTimeZone.forOffsetHours(8));
        return local.toString(DateTimeFormat.forPattern("yyyy-MM-dd"));
    }

    /**
     * 获取今天剩余秒数
     *
     * @return 剩余秒数
     */
    public static int remainingToday() {
        DateTime local = DateTime.now(DateTimeZone.forOffsetHours(8));
        MutableDateTime time = DateTime.now(DateTimeZone.forOffsetHours(8)).toMutableDateTime();
        time.setHourOfDay(0);
        time.setMinuteOfDay(0);
        time.setSecondOfDay(0);
        time.setMillisOfDay(0);

        int remaining = (int) ((local.getMillis() - time.getMillis()) / 1000);

        return 86400 - remaining;
    }

    /**
     * 获取文件链接的后缀名，小写
     *
     * @param url 文件链接
     * @return 后缀，不存在时返回空字符串
     */
    public static String getSuffix(String url) {
        if (url != null && url != "") {
            String[] res = url.split("/");
            String lastPath = res[res.length - 1];
            String[] params = lastPath.split("\\?");
            String file = params[0];
            String[] paths = file.split("\\.");
            if (paths.length > 1) {
                return paths[1].toLowerCase();
            }
        }
        return "";
    }

    /**
     * 格式化 idd，只返回数字字符串
     *
     * @param idd
     * @return
     */
    public static String formatIddCode(String idd) {
        if (idd != null) {
            return idd.trim().replace("+", "");
        }
        return "";
    }

    /**
     * 获取从某时间开始已过去多少秒
     *
     * @param dateTime
     * @return
     */
    public static int passSecond(DateTime dateTime) {
        if (dateTime.isBefore(DateTime.now())) {
            Seconds.secondsBetween(dateTime, DateTime.now());
        }
        return 0;
    }

    /**
     * 获取几个小时后过期的剩余秒数
     *
     * @param dateTime
     * @param expHours 过期
     * @return
     */
    public static int passSecond(DateTime dateTime, int expHours) {
        DateTime plusHours = dateTime.plusHours(expHours);
        if (plusHours.isAfterNow()) {
            return Seconds.secondsBetween(DateTime.now(), plusHours).getSeconds();
        }
        return 0;
    }

    /**
     * 检查 appKey 是否合法
     *
     * @param appKey
     * @return true or false
     */
    public static boolean checkApp(String appKey) {
        String[] apps = new String[]{"FAceBe8acE1A11e990a19F43a0Dae3f5", //xPocket
                "W6OecX1zIZjmYN3RpW7XJnoDBD7wWzJe", // iOS
                "e3691404-1b38-11e6-9663-34363bcc28ec", // Android
                "83f4E5C40a8211eab4f867AF8116A72a", // xTransfer iOS
                "B60b2A280a8211eab0E8530606eD24A3", // xTransfer Android
                "BBCACB1C3F5A11E783D034363BCC28EC",
                "D026Cc24afF7611E8b0D30200a05A0801",
                "6B62Db84cf8011E9A90813896c758697", // Web
                "12E0B26a0B1311e99Fc777261EC7785d",
                "Fa6be6Ee83c211eaAe7c1f07d2C91e7d"}; // backend key

        return Arrays.stream(apps).filter(x -> x.equals(appKey)).count() > 0;
    }

    /**
     * 获取 AppKey 对应的平台
     *
     * @param appKey
     * @return platform
     */
    public static String getPlatform(String appKey) {
        String platform = "default";
        if ("W6OecX1zIZjmYN3RpW7XJnoDBD7wWzJe,e3691404-1b38-11e6-9663-34363bcc28ec".contains(appKey)) {
            platform = "xCurrency";
        } else if ("83f4E5C40a8211eab4f867AF8116A72a,B60b2A280a8211eab0E8530606eD24A3".contains(appKey)) {
            platform = "xTransfer";
        } else if ("FAceBe8acE1A11e990a19F43a0Dae3f5".contains(appKey)) {
            platform = "xPocket";
        } else if ("6B62Db84cf8011E9A90813896c758697".contains(appKey)) {
            platform = "Web";
        }

        return platform;
    }

    /**
     * 判断是否 iOS
     *
     * @param appKey
     * @return true or false
     */
    public static boolean isiOS(String appKey) {
        return "W6OecX1zIZjmYN3RpW7XJnoDBD7wWzJe,83f4E5C40a8211eab4f867AF8116A72a".contains(appKey);
    }

    /**
     * 判断是否 Android
     *
     * @param appKey
     * @return true or false
     */
    public static boolean isAndroid(String appKey) {
        return "B60b2A280a8211eab0E8530606eD24A3,e3691404-1b38-11e6-9663-34363bcc28ec".contains(appKey);
    }

    /**
     * 判断是否为 Web 平台
     *
     * @param appKey
     * @return true or false
     */
    public static boolean isWeb(String appKey) {
        return "6B62Db84cf8011E9A90813896c758697".contains(appKey);
    }

    /**
     * 判断是否为后端 KEY
     *
     * @param appKey
     * @return true or false
     */
    public static boolean isBackend(String appKey) {
        return "Fa6be6Ee83c211eaAe7c1f07d2C91e7d".contains(appKey);
    }

    /**
     * 合并 iOS/Android 平台语言
     *
     * @return
     */
    public static String convertLanguage(String language) {
        switch (language) {
            case "zh-CN":
            case "zh-Hans":
                return "zh-CN,zh-Hans";
            case "zh-HK":
            case "zh-Hant":
                return "zh-HK,zh-Hant";
            default:
                return language;
        }
    }

    /**
     * 生成随机数字字符串
     *
     * @param num
     * @return
     */
    public static String randStr(int num) {
        return RandomStringUtils.randomNumeric(num);
    }

    /**
     * 生成随机字母和数字结合的名字
     *
     * @param num
     * @return
     */
    public static String randName(int num) {
        return RandomStringUtils.randomAlphanumeric(num);
    }

    /**
     * 生成订单号，组成形式为：201705081422301234，日期加 4 位随机数字字符串
     *
     * @return
     */
    public static String generatorOrderNo() {
        DateTime now = DateTime.now(DateTimeZone.forOffsetHours(8));
        DateTimeFormatter format = DateTimeFormat.forPattern("yyyyMMddHHmmss");

        return now.toString(format) + randStr(4);
    }

    /**
     * 获取文件路径中的时间，/test/1596332566523.png
     *
     * @param path 文件路径
     * @return
     */
    public static String getFilePathDate(String path) {
        DateTimeFormatter format = DateTimeFormat.forPattern(NORMAL_FORMAT);
        if (path != null && path != "") {
            String[] res = path.split("/");
            String lastPath = res[res.length - 1];
            if (lastPath.length() >= 13) {
                String timestamp = lastPath.substring(0, 13);
                DateTime dateTime = new DateTime(Long.parseLong(timestamp), DateTimeZone.forOffsetHours(0));
                return dateTime.toString(format);
            }
        }

        return DateTime.now().toString(format);
    }
}
